<?php
namespace app\controller;

use app\BaseController;
use app\model\User;
use think\facade\Config;
use think\facade\Validate;
use Firebase\JWT\JWT;

class Auth extends BaseController
{
    /**
     * 用户登录
     */
    public function login()
    {
        $data = $this->request->post();
        // 验证数据
        $validate = Validate::rule([
            'username' => 'require',
            'password' => 'require'
        ]);
        
        if (!$validate->check($data)) {
            return $this->error('参数错误：' . $validate->getError());
        }

        // 查询用户
        $user = User::where('username', $data['username'])->find();
       /* echo User::getLastSql(); die;*/
        if (!$user) {
            return $this->error('用户名不存在');
        }

        // 验证密码
        if (!$user->checkPassword($data['password'])) {
            return $this->error('密码错误');
        }
        
        // 验证状态
        if ($user->status != 1) {
            return $this->error('账号已被禁用');
        }
        
        // 更新最后登录时间
        $user->last_login_time = date('Y-m-d H:i:s');

        $user->save();
        
        // 生成Token
        $token = $this->createToken($user->id);
        
        // 获取用户权限
        $permissions = $user->getPermissions();
        
        return $this->success('登录成功', [
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'username' => $user->username,
                'name' => $user->name,
                'avatar' => $user->avatar,
                'email' => $user->email,
            ],
            'permissions' => $permissions
        ]);
    }
    
    /**
     * 用户退出
     */
    public function logout()
    {
        return $this->success('退出成功');
    }
    
    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        $userId = $this->request->userId;
        $user = User::find($userId);
        
        if (!$user) {
            return $this->error('用户不存在');
        }
        
        // 获取用户权限
        $permissions = $user->getPermissions();
        
        return $this->success('获取成功', [
            'user' => [
                'id' => $user->id,
                'username' => $user->username,
                'name' => $user->name,
                'avatar' => $user->avatar,
                'email' => $user->email,
                'phone' => $user->phone,
                'department' => $user->department,
                'position' => $user->position,
            ],
            'permissions' => $permissions
        ]);
    }
    
    /**
     * 创建Token
     * @param int $userId 用户ID
     * @return string
     */
    private function createToken($userId)
    {
        $key = Config::get('jwt.secret_key');
        $expire = Config::get('jwt.expire', 7200);
        
        $payload = [
            'iss' => 'iot_system', // 签发者
            'aud' => 'iot_user',   // 接收方
            'iat' => time(),       // 签发时间
            'nbf' => time(),       // 生效时间
            'exp' => time() + $expire, // 过期时间
            'data' => [
                'user_id' => $userId
            ]
        ];
        
        return JWT::encode($payload, $key, 'HS256');
    }
} 